<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			*{padding: 0;border: 0;margin: 0;outline: 0;box-sizing: border-box;}
			div{height: 100px;width: 100px;background-color: #e33;transition: 0.2s linear;}
		</style>
	</head>
	<body>
		<div id="box"></div>
		<script type="text/javascript">
			console.dir(window);
			var box = document.getElementById('box');
			var _top = +box.style.marginTop;
			var _left = +box.style.marginLeft;
			document.onkeydown = function(e){
				if(e.keyCode === 38){
					console.log('上');
					_top > 0 && (_top -= 100);
					box.style.marginTop = _top + 'px';
				}
				if(e.keyCode === 40){
					console.log('下');
					if(window.innerHeight - _top - 100 < 100){
						box.style.marginTop = (window.innerHeight - 100) + 'px';
					}else{
						_top < window.innerHeight - 100 && (_top += 100);
						box.style.marginTop = _top + 'px';
					}
				}
				if(e.keyCode === 37){ // 左移
					console.log('左');
					_left > 0 && (_left -= 100);
					box.style.marginLeft = _left + 'px';
				}
				if(e.keyCode === 39){// 右移
					console.log('右');
					if(window.innerWidth - _left - 100 < 100){
						box.style.marginLeft = (window.innerWidth - 100) + 'px';
					}else{
						_left < window.innerWidth - 100 && (_left += 100);
						box.style.marginLeft = _left + 'px';
					}
				}	
			}
		</script>
	</body>
</html>